package com.lizk.net.netty.decoder;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

public class Client {
	EventLoopGroup clientGroup = new NioEventLoopGroup();
	public void connect(String ip , int port){
		Bootstrap b = new Bootstrap();
		b.group(clientGroup).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChildHandler());
		try {
			ChannelFuture f = b.connect(ip, port).sync();
			f.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			clientGroup.shutdownGracefully();
		}
	}
	public class ChildHandler extends ChannelInitializer<SocketChannel>{
		@Override
		protected void initChannel(SocketChannel paramC) throws Exception {
			paramC.pipeline().addLast(new LineBasedFrameDecoder(1024));
			paramC.pipeline().addLast(new StringDecoder());
			paramC.pipeline().addLast(new ClientHandler());
		}
	}
	public class ClientHandler extends ChannelInboundHandlerAdapter{

		
		
		@Override
		public void channelActive(ChannelHandlerContext ctx) throws Exception {
			for(int i = 0 ; i < 100 ; i ++){
				byte[] reqs = "现在几点了？\r\n".getBytes();
				ByteBuf req = Unpooled.buffer(reqs.length);
				req.writeBytes(reqs);
				ctx.writeAndFlush(req);
			}
		}
		@Override
		public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
			/*ByteBuf buf = (ByteBuf) msg;
			byte[] req = new byte[buf.readableBytes()];
			buf.readBytes(req);
			String body = new String(req, "utf-8");*/
			String body = (String)msg;
			System.out.println("接受到消息：" + body);
//			ByteBuf res = Unpooled.copiedBuffer((System.currentTimeMillis() + "").getBytes());
//			ctx.write(res);
		}
		@Override
		public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
			ctx.flush();
		}

		@Override
		public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
			ctx.close();
		}
	}
	public static void main(String[] args) {
		Client c = new Client();
		c.connect("127.0.0.1", 10001);
	}
	
}
